<template>
  <div class="common-container">
    <div class="header">
        <div class="header_left">
          <el-input v-model="search_val.imei" clearable @clear="clearImei" placeholder="请输入设备编码" size="small"
            style="width: 220px;margin-right: 15px;" maxlength="20" oninput="value=value.replace(/[\u4e00-\u9fa5]/g,'')">
            <el-button slot="append" :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'" @click="searchClick">
            </el-button>
          </el-input>

          <el-popover placement="bottom" width="520" trigger="click" popper-class="popover"
            size="small" v-model="showPopover">
            <div>
              <el-form label-width="70px" style="margin: 20px 0" class="popover_from">
                <el-row>
                  <el-col :span="12">
                    <el-form-item size="small" label="租户名称">
                      <!-- v-model="tenantName" -->
                      <!-- <el-select v-model="search_val.tenantId" style="width: 410px; margin-left: 15px" filterable
                        placeholder="租户" size="small" clearable @clear="onClearEnterprise" v-loadMore="loadMore" remote
                        :remote-method="remoteMethodEnterprise" @change="enterpriseGetUnit">
                        <el-option v-for="(item, i) in enterpriseList" :key="i" :label="item.name" :value="item.id">
                        </el-option>
                        <div class="div_box" v-loading="loading" :style="loading ? '' : 'display: none;'"></div>
                      </el-select> -->

                      <el-select v-model="search_val.tenantId" filterable placeholder="租户名称" size="small"
                        style="width: 150px; margin-left: 15px" v-loadMore="loadMore" clearable
                        @change="enterpriseGetUnit">
                        <el-option v-for="(item, i) in enterpriseList" :key="i" :label="item.name" :value="item.id">
                        </el-option>
                        <div class="div_box" v-loading="loading" :style="loading ? '' : 'display: none;'"></div>
                      </el-select>

                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item size="small" label="产品类型">
                      <el-select v-model="search_val.deviceType" placeholder="产品类型" size="small" clearable
                        style="width: 150px; margin-left: 15px" @visible-change="enterpriseChange2"
                        @change="deviceTypeChange">
                        <el-option v-for="item in productList" :key="item.id" :label="item.name"
                          :value="item.deviceType">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- <el-row>
                  <el-col :span="12">
                    <el-form-item size="small" label="组织机构">
                      <el-select v-model="selectedValue" size="small" style="width: 150px; margin-left: 15px"
                        v-loadMore="loadMoreUnit" @change="changeOrgId" placeholder="组织机构" clearable filterable remote
                        :remote-method="remoteMethod" @clear="handleClear">
                        <el-option v-for="item in projectList" :label="item.orgName" :value="item.id" :key="item.id">
                        </el-option>
                        <div class="div_box" v-loading="loading" :style="loading ? '' : 'display: none;'"></div>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row> -->
                <el-row>
                  <el-col :span="12">
                    <el-form-item size="small" label="产品型号">
                      <el-select size="small" style="width: 150px; margin-left: 15px" v-loadMore="loadMore2" clearable
                        v-model="search_val.classMark" placeholder="产品型号" @change="ProductModelPage">
                        <el-option v-for="item in classMarkList" :label="item.model" :value="item.model" :key="item.id">
                        </el-option>
                        <div class="div_box" v-loading="loading2" :style="loading2 ? '' : 'display: none;'"></div>
                      </el-select></el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item size="small" label="告警类型">
                      <el-select v-model="search_val.alarmType" placeholder="告警类型" size="small" clearable
                        style="width: 150px; margin-left: 15px">
                         <el-option
                          v-for="dict in dict.type.device_alarm_type"
                          :key="dict.id"
                          :label="dict.raw.dickLabel"
                          :value="dict.raw.dickValue"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item size="small" label="告警日期">
                      <el-date-picker v-model.trim="timeArr" type="datetimerange" size="small" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
                        :default-time="['00:00:00', '23:59:59']" :picker-options="pickerOptions" popper-class="noClear"
                        :clearable="false" style="width: 410px; margin-left: 15px" @change="onChangeTime">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <div class="footer" style="text-align: right">
                <el-button size="small" @click="resetClick1" class="cancel-button">重 置</el-button>
                <el-button size="small" @click="searchClick1" class="confirm-button">确 定</el-button>
              </div>
            </div>
            <el-button size="small" slot="reference" :class="hasSearch?'elhasSearch elhasSearch2':'elhasSearch2'">
              高级搜索<i class="el-icon-search" style="margin-left: 5px; font-size: 12px"></i></el-button>
          </el-popover>
        </div>
        <div class="header_right">
          <el-button class="el_button" size="small" type="primary" icon="el-icon-upload2" style="margin-left: 15px"
            @click="addExports">
            导出
          </el-button>
        </div>
      </div>
      <div class="content" :style="user.roleName == 'TENANT_ADMIN'
        ? 'height:calc(100% - 215px)'
        : 'height:calc(100% - 65px)'
        ">
        <el-table :data="dataList" height="calc(100% - 65px)" class="table" ref="refTable" row-key="id"
          :header-cell-style="headerStyle" @sort-change="onSortChange" v-loading="loadingTable"
          element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(47, 51, 73, 0.3)">
          <template slot="empty">
            <p>{{ dataText }}</p>
          </template>
          <el-table-column align="center" label="序号" type="index" width="80" :index="indexMethod">
          </el-table-column>
          <el-table-column align="center" prop="orgName" label="联网单位" min-width="120" show-overflow-tooltip>
          </el-table-column>
          <el-table-column align="center" prop="name" label="安装点" min-width="180" show-overflow-tooltip>
          </el-table-column>
          <el-table-column align="center" prop="imei" label="设备编码" min-width="130">
          </el-table-column>
          <el-table-column align="center" prop="deviceType" label="产品类型" min-width="130">
            <template slot-scope="scope">
              {{ scope.row.deviceType | deviceTypeText }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="classMark" label="产品型号" min-width="130">
          </el-table-column>
          <el-table-column align="center" prop="alarmType" label="告警类型" min-width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.alarmType | alarmTypeText }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="count" label="告警次数" sortable="custom" min-width="100">
          </el-table-column>
          <el-table-column align="center" label="操作" width="130">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="详情" placement="bottom">
                <i @click="onDefine(scope.row)" class="iconfont xiangqing tableBtnIcon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination :page.sync="page" :limit.sync="limit" :total="total" @pagination="PageMessagePackage('init')"
          class="pagination">
        </pagination>
      </div>
      <warnRecord ref="refWarnRecord" :info="info"></warnRecord>
  </div>
</template>

<script>
import {
  reqTenantList,
  reqOrgList,
  reqAlarmStatistics,
  reqProductList,
  reqAlarmtatisticsTask,
} from "@api/api.js";
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";
import advanceSearchMixin from "./mixins/advanceSearch";
import warnRecord from "./components/warnRecord.vue";
import Tree from "@components/tree/Unit.vue";//组织机构

export default {
  dicts: ['device_alarm_type'],
  name: "service",
  components: {
    Pagination,
    warnRecord,
    Tree
  },
  mixins: [tableStyleMixin, loadMore, advanceSearchMixin],
  data() {
    return {
      //实现时间限制选择在一个月内而且不能超过当前时间
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.cuttentTime = minDate.getTime();
          if (maxDate) {
            this.cuttentTime = "";
          }
        },
        disabledDate: (time) => {
          //获取当前时间戳
          let myDate = new Date();
          let newY = myDate.getFullYear();
          let newM = myDate.getMonth() + 1;
          let newD = myDate.getDate();
          let oldTime =
            newY +
            "-" +
            (newM < 10 ? "0" + newM : newM) +
            "-" +
            (newD < 10 ? "0" + newD : newD) +
            " " +
            "23:59:59";
          // let oldTime="2022-7-5 23:59:59"
          oldTime = new Date(oldTime).getTime(); // 将中国时间转换成毫秒
          // 今天之后的时间不可选
          if (time.getTime() > oldTime) {
            //time.getTime() > Date.now()
            return true;
          }
          //选择日期范围为一个月
          if (this.cuttentTime != "") {
            const one = 30 * 24 * 3600 * 1000;
            const minTime = this.cuttentTime - one;
            const maxTime = this.cuttentTime + one;
            return time.getTime() < minTime || time.getTime() > maxTime;
          }
        },
      },
      orderTypeList: [
        {
          id: "1",
          name: "顺序",
        },
        {
          id: "2",
          name: "逆序",
        },
      ],
      search_val: {
        tenantId: "",
        imei: "",
        orgId: "",
        alarmType: "",
        deviceType: "",
        classMark: "",
        startTime: "",
        endTime: "",
        order: "",
      },
      showPopover: false, //v-model默认值是false, click激活变成true

      productList: [],
      timeArr: [],

      dataList: [],
      page: 1,
      limit: 10,
      total: 0,
      sysInstanceIndexUnit: 1,
      sysInstanceUnitTotalPages: 10,

      loadingSearch: false,
      loadingReset: false,

      enterpriseList: [],
      projectList: [],
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      flag: true,
      flag2: true,
      loading: false,
      loading2: false,
      sysInstanceIndex2: 1,
      sysInstanceTotalPages2: 10,
      orgName: "",
      selectedValue: "",

      info: {},
      tenantName: "",

      loadingTable: false,
      dataText: "",
      targetId: "",
      hasSearch:false,
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  mounted() {
    this.getPreMonth();
    this.getEnterpriseList();
    this.PageMessagePackage();
  },
  methods: {
    // 组织机构筛选
    toggleOrgId(data) {
      // console.log(data);
      this.targetId = data.orgId || ''
      this.PageMessagePackage();
    },
    // 序号
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.limit;
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      // 获取列表数据的方法
      await this.getEnterpriseList();
      this.loading = false;
    },

    // 下拉请求列表
    enterpriseChange2(val) {
      if (val) {
        this.getProductList();
      }
    },
    //   获取产品列表
    async getProductList() {
      const res = await reqProductList();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.productList = res.data.rows;
    },
    // 获取租户列表
    // async getEnterpriseList() {
    //   var res = await reqTenantList(this.sysInstanceIndex, 10, {
    //     name: this.tenantName || "",
    //   });

    //   if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
    //   this.sysInstanceTotalPages = res.data.total;
    //   this.enterpriseList = [...this.enterpriseList, ...res.data.rows];
    // },
    // 选择组织机构
    changeOrgId(e) {
      this.search_val.orgId = e;
    },
    // 清空
    handleClear() {
      this.selectedValue = "";
      this.orgName = "";
      this.sysInstanceIndex = 1;
      this.sysInstanceUnitTotalPages = 10;

      this.sysInstanceIndex = 1;
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.projectList = [];
      this.OrgList();
    },
    // 远程搜索
    // async remoteMethod(query) {
    //   this.selectedValue = query; //保留输入的值
    //   this.orgName = query;
    //   this.sysInstanceIndex2 = 1;
    //   this.sysInstanceTotalPages2 = 10;
    //   this.projectList = [];
    //   this.OrgList();
    // },
    async loadMore2() {
      if (this.sysInstanceIndex2 >= Math.ceil(this.sysInstanceTotalPages2 / 10))
        return;
      this.sysInstanceIndex2++;
      this.loading2 = true;
      // 获取列表数据的方法
      await this.OrgList();
      this.loading2 = false;
    },

    // 下拉请求列表
    enterpriseChange(val) {
      if (val && this.flag2) {
        this.OrgList();
        this.flag2 = false; //只执行一次
      }
    },
    // 获取组织机构列表
    // async OrgList() {
    //   var res = await reqOrgList(this.sysInstanceIndex2, 10, {
    //     userId: this.user.userId,
    //     roleName: this.user.roleName,
    //     tenantId: this.user.tenantId,
    //     orgName: this.orgName,
    //   });
    //   if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
    //   this.sysInstanceTotalPages2 = res.data.total;
    //   this.projectList = [...this.projectList, ...res.data.rows];
    // },
    clearStateList() {
      this.page = 1;
      this.limit = 10;
      this.PageMessagePackage();
    },
    // 告警统计列表
    async PageMessagePackage() {
      this.loadingTable = true;
      const res = await reqAlarmStatistics(this.page, this.limit, {
        tenantId: this.search_val.tenantId,
        orgId: this.targetId,
        startTime: this.search_val.startTime,
        endTime: this.search_val.endTime,
        alarmType: this.search_val.alarmType,
        deviceType: this.search_val.deviceType,
        classMark: this.search_val.classMark,
        order: this.search_val.order,
        imei: this.search_val.imei,
      });
      this.loadingTable = false;
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.hasSearch=(this.search_val.tenantId || this.search_val.startTime|| this.search_val.endTime || this.search_val.alarmType || this.search_val.deviceType  || this.search_val.classMark  ) ? true : false
      let { rows, total } = res.data;
      if (!rows.length) {
        this.dataText = "暂无数据";
      }
      this.dataList = rows;
      this.total = total;
    },
    // 选择时间
    onChangeTime(e) {
      if (e && e.length) {
        this.timeArr = [e[0], e[1]];
        this.search_val.startTime = e[0];
        this.search_val.endTime = e[1];
      }
    },
    // 告警次数次序
    onSortChange(e) {
      if (!e.order) return;
      this.page = 1;
      let { order, column } = e;
      if (order == "ascending") {
        this.search_val.order = 1;
      } else if (order == "descending") {
        this.search_val.order = 2;
      }
      this.PageMessagePackage();
    },
    // 查询
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      await this.PageMessagePackage();
      this.loadingSearch = false;
    },
    clearImei() {
      this.PageMessagePackage();
    },
    // 获取近一个月的时间
    getPreMonth() {
      // 获取今天的日期
      var today = new Date();

      // 计算一个月后的日期
      var oneMonthLater = new Date(today);
      oneMonthLater.setMonth(oneMonthLater.getMonth() - 1);

      // 格式化日期为年-月-日格式
      function formatDate(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1).toString().padStart(2, "0"); // getMonth() 返回的月份是从0开始的，所以需要+1
        var day = date.getDate().toString().padStart(2, "0");
        return `${year}-${month}-${day}`;
      }

      // 使用函数格式化日期
      var formattedDate = formatDate(oneMonthLater);
      // 使用函数格式化当前日期
      var formattedCurrentDate = formatDate(today);
      this.search_val.startTime = `${formattedDate} 00:00:00`;
      this.search_val.endTime = `${formattedCurrentDate} 23:59:59`;
      this.timeArr = [this.search_val.startTime, this.search_val.endTime];
    },
    // 详情
    onDefine(row) {
      row.startTime = this.search_val.startTime;
      row.endTime = this.search_val.endTime;
      this.info = JSON.parse(JSON.stringify(row));
      this.$refs.refWarnRecord.dialogVisible = true;
    },

    // 导出
    async addExports() {
      const result = await this.$confirm(
        "此操作将导出告警统计信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => { });
      if (result !== "confirm") return;
      const res = await reqAlarmtatisticsTask({
        tenantId: this.search_val.tenantId,
        imei: this.search_val.imei,
        orgId: this.search_val.orgId,
        alarmType: this.search_val.alarmType,
        deviceType: this.search_val.deviceType,
        classMark: this.search_val.classMark,
        startTime: this.search_val.startTime,
        endTime: this.search_val.endTime,
        order: this.search_val.order,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("导出成功，请在任务管理中查看");
      this.$router.push({ name: "exportTask" });
    },
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");
@import url("~@views/style/tree.less"); //左侧组织机构样式

.common-container {
  box-shadow: none !important;

  // background-color: transparent;
  .header {
    background-color: @primaryHeaderBgcolor;
    border-radius: 6px 6px 0 0;
    position: relative;
    width: 100%;
    justify-content: left;
    display: flex;
    justify-content: space-between;
  }
}

.statistics {
  min-height: 130px;
  width: 100%;
  color: @primaryThemeTxtColor;
  display: flex;
  justify-content: space-between;
  padding: 8px 25px 25px 25px;
  box-sizing: border-box;
  background: @primaryBgcolor2;

  .item {
    box-sizing: border-box;
    width: 31%;
    background: @primarywarn;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    >div:first-of-type {
      font-size: 40px;
      font-weight: 700;
      font-family: electronicFont;
    }

    >div:last-of-type {
      font-size: 16px;
      color: #aaa;
    }
  }
}

.popover_from {
  color: @primaryThemeTxtColor2;
  padding: 0px;
}

.popover_footer {
  width: 100%;
  display: flex;
  justify-content: center;
}

.content {
  height: calc(100% - 61px) !important;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 190px;
  z-index: 9999;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束

.el-icon-view {
  font-size: 18px;
  cursor: pointer;

  &:hover {
    color: #7367f0;
  }
}

/*日期时间组件不显示 清空按钮*/
::v-deep .noClear .el-picker-panel__footer .el-button .el-picker-panel__link-btn .el-button--text .el-button--mini {
  display: none !important;
}

// 日期控件颜色
::v-deep .el-range-editor .el-range-input {
  background: @primaryHeaderBgcolor;
  color: @primaryContentTxt;
}

//   &::placeholder {
//     color: @primaryFFFColor5 !important;
//   }

//   &::-webkit-input-placeholder {
//     color: @primaryFFFColor5 !important;
//   }

//   &:-moz-placeholder {
//     color: @primaryFFFColor5 !important;
//   }

//   &::-moz-placeholder {
//     color: @primaryFFFColor5 !important;
//   }

//   &:-ms-input-placeholder {
//     color: @primaryFFFColor5 !important;
//   }
// }

// 高级搜索
::v-deep .el-button--primary {
  background-color: #7367f0;
  border: 1px solid #7367f0;
  color: #fff;
}

::v-deep .popover_from .el-form-item__label {
  color: @primaryThemeTxtColor2;
  padding: 0px;
}

::v-deep .el-input__inner {
  color: var(--primaryContentTxt, #f1f1f1) !important;
}

::v-deep .el-button--small {
  border: none;
}
</style>
